import { useState, lazy, Suspense, useRef, useEffect, useMemo } from 'react'
import { Button, Input, Tooltip, message } from 'antd'
import { QuestionCircleOutlined } from '@ant-design/icons'
import bus from '../../../utils/eventBus'
import { useSelector } from 'react-redux'
import empty from '../../../assets/task/empty.png'
import { secretOptions } from "../../../utils/constant";
import './index.scss'
const LdListItem = lazy(() => import('../../../components/LdListItem'))
const Queue = () => {
    const { id = '', enableRecoveryPermission = false, hasRecoveryPermission = false } = useSelector((state: any) => state.userReducer.userInfo)
    const [taskArray, setTaskArray] = useState<any[]>([])
    const timer = useRef<any>(null)
    const paperParams = useRef([
        {
            label: "密级",
            value: "",
            model: "classifiedLevel",
        },
        { label: "份数", value: "", model: "currPart" }, //格式:1/6
        { label: "责任人", value: "", model: "oper" },
    ])
    const toolTipContent = useMemo(() => {
        if (!enableRecoveryPermission) return '手动输入只能回收登录人文件'
        if (hasRecoveryPermission) return '手动输入回收文件'
        if (!hasRecoveryPermission) return '暂无权限回收文件'
    }, [enableRecoveryPermission, hasRecoveryPermission])
    const handleSearch = (e: any) => {
        if (e.key === 'Enter' && e.target.value) {
            timer.current && clearTimeout(timer.current)
            const params = {
                currentPage: 0,
                pageSize: 0,
                isScan: false,
                responsible: id,
                keyword: e.target.value,
            }
            timer.current = setTimeout(() => {
                window.chromePro.getUnrecoveryInfo(
                    JSON.stringify(params)
                );
            }, 1000)
        }
    }
    const getGunDataFinished = (data: any) => {
        if (data.code === 200) {
            const res = data.data.split("-");
            window.chromePro.getUnrecoveryInfo(
                JSON.stringify({
                    currentPage: 0,
                    pageSize: 0,
                    isScan: true,
                    responsible: id,
                    keyword: data.data
                })
            );
        } else {
            message.error(data.msg);
        }
    }
    const handleDelete = (i: number) => {
        setTaskArray(origin => {
            return origin.splice(i, 1)
        })
    }
    const commitRecoveryFinished = (data: any) => {
        if (data.code === 200) {
            setTaskArray([])
            message.success("回收成功");
        } else {
            message.error(data.msg);
        }
    }
    const getUnrecoveryInfoFinished = (data: any) => {
        if (data.code === 200) {
            if (!data.data.length) {
                message.error('没有查询到对应的文件！！！');
                return;
            }
            data.data = data.data.map((res: any) => {
                return {
                    ...res,
                    title: res.fileTitle,
                    classifiedLevel: secretOptions.find((item) => item.value === res.classifiedLevel)
                        ?.label,
                    createdTime: res.fileCreateTime,
                    currPart: res.currentPart + '/' + res.part
                };
            });
            setTaskArray(origin => {
                if (origin.find((item) => !!data.data.find((res: any) => item.queueId === res.queueId))) {
                    message.warning("重复添加！！！");
                    return [...origin]
                } else {
                    message.success('文件添加成功')
                    return [...data.data, ...origin]
                }
            })
        } else {
            message.error(data.msg);
        }
    }
    const handleSubmit = () => {
        if (!taskArray.length) {
            message.warning("暂无可回收的文件");
            return;
        }
        window.chromePro.commitRecovery(
            JSON.stringify({
                data: taskArray.map((res) => res.identify),
            })
        );
    }
    useEffect(() => {
        bus.addListener("getUnrecoveryInfoFinished", getUnrecoveryInfoFinished);
        bus.addListener("commitRecoveryFinished", commitRecoveryFinished);
        bus.addListener("getGunDataFinished", getGunDataFinished);
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener("getUnrecoveryInfoFinished", getUnrecoveryInfoFinished);
            bus.removeListener("commitRecoveryFinished", commitRecoveryFinished);
            bus.removeListener("getGunDataFinished", getGunDataFinished);
        }
    }, [])
    return (
        <>
            <div className="task-box">
                <div className="w100 h100">
                    <div className="task-list-container">
                        <div className="task-list">
                            <div className="list-header">
                                <div className="h-left">
                                    <Input placeholder="请输入条码,回车检索" onKeyDown={handleSearch}></Input>
                                    <Tooltip overlayClassName='tooltip-power' color="white" title={toolTipContent} placement="right">
                                        <QuestionCircleOutlined style={{ marginLeft: '10px' }} />
                                    </Tooltip>
                                </div>
                                <div className="h-right">
                                    <Button onClick={handleSubmit} type="primary">提交回收</Button>
                                </div>
                            </div>
                            {
                                taskArray.length ?
                                    <div className='ld-list-box'>
                                        {
                                            taskArray.map((item: any, index: number) => {
                                                return (
                                                    <LdListItem index={index + 1} paperParams={paperParams.current} mode={'print'} taskItem={item}
                                                        key={item.identify}>
                                                        <Button danger onClick={() => handleDelete(index)}>删除</Button>
                                                    </LdListItem>
                                                )
                                            })
                                        }
                                    </div>
                                    :
                                    <div className="empty-content flex-center align-center">
                                        <div>
                                            <img draggable={false} src={empty} width="238px" />
                                            <div style={{
                                                width: '100%',
                                                textAlign: 'center',
                                                color: 'rgba(137, 147, 154, 100)',
                                                fontSize: '14px'
                                            }} className="mt-10">
                                                暂无任务队列
                                            </div>
                                        </div>
                                    </div>
                            }
                        </div>
                    </div>
                </div>
            </div>
        </>
    )
}
export default Queue